package com.dqlp.yf.rabbitmq.receive;

import com.dqlp.yf.rabbitmq.constant.MqConstant;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @program: rabbitmq
 * @description: 消费者
 * @author: andy
 * @create: 2019-09-07 10:46
 */
@Component
@Slf4j
public class Customer {
    @RabbitListener(queues = MqConstant.TEST_QUEUE)
    public void customer( Message message, Channel channel) throws IOException {
        /**
         * prefetchSize：0
         * prefetchCount：会告诉RabbitMQ不要同时给一个消费者推送多于N个消息，即一旦有N个消息还没有ack，则该consumer将block掉，直到有消息ack
         * global：true\false 是否将上面设置应用于channel，简单点说，就是上面限制是channel级别的还是consumer级别
         * 备注：据说prefetchSize 和global这两项，rabbitmq没有实现，暂且不研究
         */
        channel.basicQos(0,10,false);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        log.info("-----------consume message----------");
        log.info("body: " + new String(message.getBody()));
        Integer num = (Integer)message.getMessageProperties().getHeaders().get("num");
      //  Integer priority = (Integer)message.getMessageProperties().getPriority();
        log.info("deliveryTag:{},num:{}",deliveryTag,num);
        // System.out.println("deliveryTag为："+deliveryTag);
        if (num == 0) {
            /**
             * deliveryTag:该消息的index
             * multiple：是否批量.true:将一次性拒绝所有小于deliveryTag的消息。
             * requeue：被拒绝的是否重新入队列
             */
            channel.basicNack(deliveryTag, false, false);
        } else {
            /**
             * deliveryTag:该消息的index
             * multiple：是否批量.true:将一次性ack所有小于deliveryTag的消息。
             */
            channel.basicAck(deliveryTag,false);
        }
    }

}
